package com.rain.activity.utils;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Rain on 2016/4/19.
 */
public class QuestionDAO {
    public static void insertData(Map<String,Object> map){
        String sql = "insert into que_ans(question,answer) values(?,?)";
        Globals.db.getWritableDatabase().execSQL(sql, new Object[]{map.get("que"), map.get("ans")});
    }
    public static  List<Map<String,Object>> loadData(){
        List<Map<String,Object>> values = new ArrayList<>();
        String sql = "select id,question ,answer from que_ans";
        Cursor c =  Globals.db.getReadableDatabase().rawQuery(sql, null);
        c.moveToFirst();

        while(!c.isAfterLast()){
            Map<String,Object> map = new HashMap<>();
            map.put("que",c.getString(1));
            map.put("ans",c.getString(2));
            values.add(map);
            c.moveToNext();
        }c.close();
        return values;
    }
    //分页读取数据
    public static  List<Map<String,Object>> loadDataPage(int pageNum,int pageSize ,String keyword){
        List<Map<String,Object>> values = new ArrayList<>();
        String sql = "select id,question ,answer from que_ans where question like ? limit ?,?";
        Cursor c =  Globals.db.getReadableDatabase().rawQuery(sql,new String[]{"%"+keyword+"%",pageSize*pageNum-pageSize+"",pageSize+""});
        c.moveToFirst();

        while(!c.isAfterLast()){
            Map<String,Object> map = new HashMap<>();
            map.put("que",c.getString(1));
            map.put("ans",c.getString(2));
            map.put("showflag",false);
            values.add(map);
            c.moveToNext();
        }c.close();
        return values;
    }

    public static int getPageCount(String keyword) {
        int recordCount =0;
        String sql = "select count(*) from que_ans where question like ?";
        Cursor  c = Globals.db.getReadableDatabase().rawQuery(sql,new String[]{"%"+keyword+"%"});
        c.moveToFirst();
        recordCount = c.getInt(0);
        c.close();
        return recordCount;
    }
    public static void delete(){
        String sql = "delete from que_ans";
        Globals.db.getWritableDatabase().execSQL(sql);
    }
}
